import pymongo.errors
from pymongo import MongoClient


class ConnectMongo():
    def __init__(self, uri, user, pwd, db_name):
        self.client = MongoClient(f"mongodb://{user}:{pwd}@{uri}/?authMechanism=DEFAULT", connectTimeoutMS=5000)
        try:
            self.client.server_info()
        except pymongo.errors.ServerSelectionTimeoutError as exc:
            raise Exception("失败")
        self.db_name = db_name
        self.database = self.client[self.db_name]

    def demo(self, query, collect_name):
        self.collection = self.database[collect_name]
        return self.collection.find_one(query)


